﻿// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Novel.Sync.Service;
using Novel.Sync.SyncUtil;
using Serilog;
using Serilog.Events;
using Serilog.Filters;
using SqlSugar;
using System.Text;
using XjjXmm.FrameWork.Cache;



#if DEBUG
var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.development.json", false, true).Build();
#else
var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.prod.json", false, true).Build();
#endif

NovelSync.ExportFolder = config["exportFolder"];


const string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] ({ThreadId}) {Message:lj}{NewLine}{Exception}";

#region log
LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
            .MinimumLevel.Information()

            //.Enrich.WithProperty("SourceContext", null) //加入属性SourceContext，也就运行时是调用Logger的具体类
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .Enrich.WithThreadId()
            .Enrich.WithThreadName()
            ;

loggerConfiguration = loggerConfiguration
              .WriteTo.Console(outputTemplate: outputTemplate)
              .WriteTo.File("log/log.txt", rollingInterval: RollingInterval.Day)
              .WriteTo
                   .Logger(lc => lc.Filter.ByIncludingOnly(t => t.Level == LogEventLevel.Error)
                    .WriteTo.File($"log/error.txt", rollingInterval: RollingInterval.Day));

Log.Logger = loggerConfiguration.CreateLogger();
#endregion

//var connectonString = "Server=192.168.88.25; Port=3306; Database=novel; Uid=root; Pwd=123456; Charset=utf8mb4;";
var sqlSugar = new SqlSugarScope(new List<ConnectionConfig> {
    new ConnectionConfig()
        {
            ConfigId="0",
            DbType = SqlSugar.DbType.MySql,
            ConnectionString = config["db1:connectionString"],
            IsAutoCloseConnection = true,

        },
    new ConnectionConfig()
        {
            ConfigId="1",
            DbType = SqlSugar.DbType.MySql,
            ConnectionString = config["db2:connectionString"],
            IsAutoCloseConnection = true,
        }
},
    db =>
    {
        //单例参数配置，所有上下文生效
        db.Aop.OnLogExecuting = (sql, pars) =>
        {
            Log.Debug($"Sql:{sql}\r\n paramters: {JsonConvert.SerializeObject(pars)}");
            //App.Logger.Debug($"Sql:{sql}\r\n paramters: {JsonConvert.SerializeObject(pars)}");
            //Console.WriteLine(sql);//输出sql
            //Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));//参数
        };
        db.GetConnection("1").CurrentConnectionConfig.ConfigureExternalServices.SplitTableService = new WordSplitService();
    }
 );
//sqlSugar.DbMaintenance.CreateDatabase();
//sqlSugar.CodeFirst.InitTables(typeof(NovelEntity));
//sqlSugar.CodeFirst.InitTables(typeof(Chapter));

var builder = new HostBuilder();

builder.ConfigureServices((hostContext, services) =>
{

    services.AddSingleton<SqlSugarScope>(sqlSugar);

    services.AddSingleton<NovelSync>();
    // services.AddSingleton<ILogger>(Log.Logger);

}).UseConsoleLifetime();


var host = builder.UseSerilog().Build();

//await RedisClient.Instance.Init("192.168.88.25:6379");
//await RedisClient.Instance.Init("192.168.1.244:6379");


//Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

//RegistHelper.RunSpider(host.Services);
//RegistHelper.Export(host.Services);
var myService = host.Services.GetService<NovelSync>();
 myService.Run();
//myService[0].Run();
//myService[1].Run();
//myService[2].Run();
//myService[3].Run();


host.Run();
